import java.io.*;
import java.net.*;
/**
 * @author: gao
 * @create-date: 2025/5/22 20:16
 */

public class Server {
    public static void main(String[] args) {
        int port = 5000;
        ServerSocket serverSocket = null;
        Socket clientSocket = null;

        try {
            serverSocket = new ServerSocket(port);
            System.out.println("Server listening on port " + port + "...");

            while (true) {
                clientSocket = serverSocket.accept();
                System.out.println("Client connected from: " + clientSocket.getInetAddress().getHostAddress());

                OutputStream os = clientSocket.getOutputStream();
                PrintWriter pw = new PrintWriter(os, true);
                pw.println("Hello from the server!");
                System.out.println("Sent 'Hello' to client.");


                clientSocket.close();
                System.out.println("Client connection closed.");
            }

        } catch (IOException e) {
            System.err.println("Server error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (serverSocket != null && !serverSocket.isClosed()) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                System.err.println("Error closing server socket: " + e.getMessage());
            }
        }
    }
}